--
-- Author: shineflag
-- Date: 2018-01-19 09:57:25
--
-- 与redis及mysql相关的数据 改动

--
-- Author: shineflag
-- Date: 2017-12-29 10:46:58
--
-- 开奖的历史数据

local skynet = require("skynet")
local log = require("log")
local json = require("json")
local cts = require("constants")
local redis = require "skynet.db.redis"
local mysql = require "skynet.db.mysql"
local sconf = require("server_conf")


local TAG = "DBDATA"

local poker_db   --mysql数据库
local rdb


local meta = {}
local CMD = {}

function meta.init()
	meta.connect_poker_db()
	meta.redis_connect()
end


--连接mysql 
function meta.connect_poker_db()
	local function on_connect(db)
		db:query("set charset utf8mb4")
		db:query("set names utf8") 
		log.e(TAG, "poker db connected!")
	end

	local mconf = require("mysql_conf")

	log.e(TAG,"start connect mysql %s:%d",mconf.host, mconf.port)
	poker_db = mysql.connect({
		host = mconf.host,
		port = mconf.port,
		database = mconf.database,
		user = mconf.user,
		password = mconf.password,
		max_packet_size=1024*1024,
		on_connect=on_connect
		})

	if not poker_db then
		log.e(TAG,"failed to connect db")
		skynet.exit()
	end
end

--连接redis
function meta.redis_connect()
	local rconfs = require("redis_conf")
	local rport = sconf["redis_mdata"]
	local rconf = rconfs[rport]
	local conf = {
		host = rconf.host,
		port = rconf.port,
		db = 0
	}
	log.e(TAG,"start connect redis %s:%d",conf.host, conf.port)
	rdb = redis.connect(conf)
end


--设置所有以keypre为前缀的key的生命周期
function CMD.expire_all_keypre( keypre, timeout )
	local ret = rdb:keys(keypre .. "*")  --ret: {key1,key2}
	log.d(TAG,"keys %s count[%d]", keypre .. "*", #ret)
	for k, v in pairs(ret) do 
		ret = rdb:expire(v, timeout)
		log.d(TAG,"expire %s %s ret[%s]", v, timeout, ret)
	end
end

--设置所有以keypre为前缀的key的生命周期
function CMD.del_all_keypre( keypre )
	local ret = rdb:keys(keypre .. "*")  --ret: {key1,key2}
	log.d(TAG,"keys %s count[%d]", keypre .. "*", #ret)
	for k, v in pairs(ret) do 
		ret = rdb:del(v)
		log.d(TAG,"del %s ret[%s]", v, ret)
	end
end





skynet.start(function()
	meta.init()
	skynet.dispatch("lua", function( session,address, cmd,... )
		log.d(TAG,"recive address[%x] cmd[%s]",address, cmd)
		local f = CMD[cmd]
		if f then
			if session ~= 0 then
		   		skynet.ret(skynet.pack( f(...) ) )
		   	else
		   		f(...)
		   	end 
		else
		    log.e(TAG,string.format("address[%d] call not exist cmd[%s] ",address,cmd) )
	    end
	end)



end)
